package com.ms.base.jdbc.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.util.Objects;

/**
 * <b>description</b>：读写分离拦截器 <br>
 * <b>time</b>：2018-07-18 15:34 <br>
 * <b>author</b>： ready likun_557@163.com
 */
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE) //在事务拦截器之前
public class DsInterceptor {

    @Pointcut("target(com.ms.base.jdbc.service.IService)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //判断是否是第一次进来,用于处理事务嵌套
        boolean isFirst = false;
        try {
            if (DsContextHolder.getDsType() == null) {
                isFirst = true;
            }
            if(isFirst) {
                Object[] args = pjp.getArgs();
                Object last;
                if (Objects.nonNull(args) && args.length > 0 && (last = args[args.length - 1]) != null && last.equals(DsType.SLAVE)) {
                    DsContextHolder.slave();
                } else {
                    DsContextHolder.master();
                }
            }
            Object o = pjp.proceed();
            return o;
        } finally {
            if(isFirst) {
                DsContextHolder.clearDsType();
            }
        }
    }
}